package com.example.controller;

import com.example.bean.Account;
import com.example.bean.User;
import com.example.service.AccountService;
import com.example.service.LoginCheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {

    @Autowired
    private AccountService accountService;

    @Autowired
    LoginCheckService loginCheckService;

    @GetMapping("/account")
    @ResponseBody
    public Account getAccount(@RequestParam("id") int id){

        return accountService.getAccount(id);
    }

    @GetMapping(value = {"/", "/login"})
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String userLogin(User user, Model model, HttpSession session) {
        int flag = loginCheckService.loginCheck(user);
        if (flag == 1) {
            //将登录的用户密码存储起来
            session.setAttribute("loginUser", user);
            // 重定向，避免表单重复提交
            return "redirect:main.html";
        }else {
            model.addAttribute("msg", "密码错误，请重新登录");
            return "login";
        }

    }

    @GetMapping("/main.html")
    public String mainPage(HttpSession session, Model model) {
        return "main";
    }
}
